<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-if="editInfo.key === 'gender'"
                 :rules="[{ required: true, message: `请选择${editInfo.name}` }]"
                 :name="editInfo.key"
                 :label="editInfo.name">
        <template #input>
          <van-radio-group v-model="editInfo.value" direction="horizontal">
            <van-radio name="0">男</van-radio>
            <van-radio name="1">女</van-radio>
            <van-radio name="2">保密</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-else-if="editInfo.key === 'avatarUrl'"
                 :rules="[{ required: true, message: `请上传${editInfo.name}` }]"
                 :name="editInfo.key"
                 :label="editInfo.name">
        <template #input>
          <van-uploader v-model="avatarUrls" :max-count="1" :before-read="beforeRead" :max-size="500 * 1024" @oversize="onOversize"
                        :after-read="afterRead" :before-delete="beforeDelete"/>
        </template>
      </van-field>
      <van-field v-else-if="editInfo.key === 'tags'"
                 :rules="[{ validator, message: '请至少选择一个标签' }]"
                 :name="editInfo.key"
                 :label="editInfo.name">
        <template #input>
          <div style="display: flex;flex-wrap: wrap;">
            <van-tag style="margin: 0 0 10px 10px" v-for="tag in activeIds" closeable size="large" type="primary"
                     @close="onTagClose(tag)">
              {{ tag }}
            </van-tag>
          </div>
        </template>
      </van-field>
      <van-field
          v-else
          v-model="editInfo.value"
          autosize
          type="textarea"
          :name="editInfo.key"
          :label="editInfo.name"
          :placeholder="`请输入${editInfo.name}`"
          :rules="[{ required: true, message: `请填写${editInfo.name}` },{ pattern, message: `${editInfo.name}格式错误` }]"
      />
    </van-cell-group>
    <van-divider v-if="editInfo.key === 'tags'" style="position: relative;left:-40px" content-position="left">选择标签</van-divider>
    <van-tree-select
        v-if="editInfo.key === 'tags'"
        v-model:active-id="activeIds"
        v-model:main-active-index="activeIndex"
        :items="tagList"
    />
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showSuccessToast} from "vant/lib/toast/function-call";
import {closeToast, showFailToast, showLoadingToast} from "vant/es";
import {bucket, cos, region} from "../config/cos";

const route = useRoute();
const editInfo = ref({
  key: route.query.key,
  name: route.query.name,
  value: route.query.value
})
const router = useRouter();
const onSubmit = async () => {
  showLoadingToast({message: '正在提交...', forbidClick: true, duration: 0});
  let id;
  const res = await myAxios.get('/user-manage/currentUser') as any;
  if (res) {
    id = res.data.id;
  }
  const response = await myAxios.post('/user-manage/editInfo', {
    id: id,
    [editInfo.value.key]: editInfo.value.key === 'tags' ? JSON.stringify(activeIds.value) : editInfo.value.value
  }) as any;
  closeToast();
  if (response) {
    router.replace('/user-info');
    showSuccessToast('修改成功');
  }
};
const avatarUrls = ref([{url: editInfo.value.value}]);
const originalTagList = [
  {
    text: '语言',
    children: [
      {text: 'java', id: 'java'},
      {text: 'phyton', id: 'phyton'},
      {text: 'c++', id: 'c++'},
      {text: 'c#', id: 'c#'},
      {text: 'c', id: 'c'},
      {text: 'go', id: 'go'},
    ],
  },
  {
    text: '性别',
    children: [
      {text: '男', id: '男'},
      {text: '女', id: '女'},
      {text: '保密', id: '保密'},
    ],
  },
  {
    text: '年纪',
    children: [
      {text: '大一', id: '大一'},
      {text: '大二', id: '大二'},
      {text: '大三', id: '大三'},
      {text: '大四', id: '大四'},
      {text: '研一', id: '研一'},
      {text: '研二', id: '研二'},
      {text: '研三', id: '研三'},
    ],
  },
  {
    text: '工作状态',
    children: [
      {text: '待业', id: '待业'},
      {text: '在职', id: '在职'},
      {text: '在校', id: '在校'},
    ],
  },
  {
    text: '职位',
    children: [
      {text: '前端', id: '前端'},
      {text: '后端', id: '后端'},
      {text: '全栈', id: '全栈'},
      {text: '大数据', id: '大数据'},
      {text: '算法', id: '算法'},
    ],
  }
];
const tagList = ref(originalTagList);
const activeIds = ref(editInfo.value.key === 'tags' ? editInfo.value.value?.split(',').filter(Boolean) : []);
const activeIndex = ref(0);
const onTagClose = (tag) => {
  activeIds.value = activeIds.value.filter((t) => t !== tag);
};
const validator = () => {
  return activeIds.value.length > 0;
};
const pattern = editInfo.value.key === 'phone' ? /^1[3-9]\d{9}$/ : editInfo.value.key === 'email' ? /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/ : null;
const beforeRead = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  if (!isJPG && !isPNG) {
    showFailToast('请上传 JPG/PNG 格式图片');
    return false;
  }
  return true;
};
const onOversize = () => {
  showFailToast('图片大小不能超过 500kb');
};
const lastFileName = ref('');
const beforeDelete = (file) => {
  lastFileName.value = file.url.split('/').pop();
  return true;
};
const afterRead = (file) => {
  // 删除旧文件
  if (lastFileName.value !== 'user-default.jpeg') {
    cos.deleteObject({
      Bucket: bucket,
      Region: region,
      Key: lastFileName.value, // 要删除的文件名称
    }, (delErr) => {
      if (delErr) {
        console.error('删除旧图片失败:', delErr);
      }
    });
  }
  // 创建一个临时的Blob对象，用于上传
  const blob = new Blob([file.file]);
  // 上传文件到cos
  cos.putObject({
    Bucket: bucket,
    Region: region,
    Key: file.file.name, // 文件名称，必须带有后缀
    Body: blob, // 文件体积，直接上传Blob对象
  }, (err, data) => {
    if (!err) {
      editInfo.value.value = 'https://' + data.Location;
    } else {
      showFailToast('上传失败');
      console.error(err);
    }
  });

};
</script>
